#include <QTime>
#include <QDebug>
#include "logger.h"

/*static*/ NCA_EXPORT FILE * Logger::stream = stdout;

Logger::Logger()
  {
  logToStdout();
  qInstallMessageHandler(&Logger::log);
  }

Logger::~Logger()
  {
  if (stream != stdout && stream != nullptr)
    fclose(stream);
  }

void Logger::logToFile(QString name)
  {
  if (stream != stdout && stream != nullptr)
    fclose(stream);

  stream = fopen(name.toStdString().c_str(), "w");
  }

void Logger::logToStdout()
  {
  if (stream != stdout && stream != nullptr)
    fclose(stream);

  stream = stdout;
  }

void Logger::log(QtMsgType type, const QMessageLogContext &context, const QString &msg)
  {
  QString prefix = "[" +  QTime::currentTime().toString() + "] ";
  QString sAppendix = msg;
  QString localMsg;

  switch (type) {
    case QtDebugMsg:
      localMsg = prefix + "Debug: " + sAppendix;
      break;
    case QtWarningMsg:
      localMsg = prefix + "Warning: " + sAppendix;
      break;
    case QtCriticalMsg:
      localMsg = prefix + "CRITICAL: " + sAppendix + " (" + context.file + ", " + QString::number(context.line) + ");";
      Logger::instance().error(localMsg);
      break;
    case QtFatalMsg:
      localMsg = prefix + "FATAL: " + sAppendix + " (" + context.file + ", " + QString::number(context.line) + ");";
      Logger::instance().error(localMsg);
      break; //abort;
    }

  fprintf(stream, "%s\n", localMsg.toLocal8Bit().constData());
  fflush(stream);
  }
